package com.seari.custody.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.seari.custody.bean.File;
import com.seari.custody.bean.Project;
import com.seari.custody.bean.TechnicalAccessory;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.constant.BusinessConstant;
import com.seari.custody.constant.MessageConstant;
import com.seari.custody.pojo.MessageBean;
import com.seari.custody.service.ReportProjectService;
import com.seari.custody.service.TechnicalAdviceService;
import com.seari.custody.util.HandlerNullUtils;
import com.seari.custody.util.JwtTokenUtils;
import com.seari.custody.util.UUIDUtils;
import io.minio.ObjectStat;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.seari.custody.util.JwtTokenUtils.TOKEN_HEADER;

@RestController
@Slf4j
public class ReportProjectController {

    @Autowired
    private ReportProjectService reportProjectService;

    @Autowired
    private TechnicalAdviceService technicalAdviceService;

    @Value("${minio.projectotherattach.bucket}")
    private String projectotherattach;

    @Autowired
    private MinIoUtil minIoUtil;

    /**
     * 添加项目信息
     * 报审系统下发到技审系统
     *
     * @param project
     * @return
     */
    @RequestMapping(value = "/report/issueProject")
    public MessageBean addIssueProject(@Valid @RequestBody Project project) {
        log.info("addIssueProject===" + project);
        MessageBean messageBean = new MessageBean();
        try {
            String uuid = UUIDUtils.getUUID();
            project.setUuid(uuid);
            // 技审意见初稿待生成
            project.setReviewStatus(BusinessConstant.REVIEW_STATUS_DBMS);
            project.setFlowStatus(BusinessConstant.FLOW_STATUS_TO_DCL);
            project.setOutlineStatus(BusinessConstant.Monitoring_THE_OUTLINT);
            project.setReconstructionStatus(BusinessConstant.WITHRECONSTRUCTION);
            //根据项目ID和项目类型判断是否重复
            int count = reportProjectService.getProjectNumByNo(project.getNo(), project.getType());
            List<File> files = project.getFiles();
            int a = 0;
            for (File file : files) {
                String fileI = UUIDUtils.getUUID();
                file.setId(fileI);//技审文件ID
                file.setProjectUuid(uuid); //技审项目编号
                file.setNo(project.getNo()); //项目编号
                file.setOutlineNumber(BusinessConstant.OUTLINENUMBER);
                file.setFlowNumber(BusinessConstant.FLOWNUMBER);
                //对文件名进行修改
                Boolean a1 = file.getFiletype().contains("工程信息概况");
                Boolean a2 = file.getExtName().contains("docx");
                Boolean a3 = !file.getFileEmcId().equals("");
                if (a1 == true && a2 == true && a3 == true) {
                    a++;
                }
            }
            // 判断是否满足:工程信息概括\docx文件\包含文件编号
            if (a < 1) {
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("没有工程信息概括文件请重新上传，请重新上传");
                return messageBean;
            }
            // 判断本地是否历史项目信息  没有直接插入
            if (count == 0) {
                project.setVersionType(BusinessConstant.VERSION_TYPE_NEW);
                project.setTechnicalExist(BusinessConstant.TECHNiICAL_REVIEW_EXIST_YES);
                project.setOutlineExist(project.getOutlineExist());
                reportProjectService.addIssueProject(project);
                //判断报审过来的文件是否为空
                if (!HandlerNullUtils.objectIsNull(files)) {
                    reportProjectService.addFileInfo(files, project.getManagerNumber());
                }
            } else {
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("推送数据已推送,不可重复推送");
                return messageBean;
            }
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("技审系统添加项目信息成功 ");
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("技审系统添加项目信息失败");
        }
        return messageBean;
    }


    /**
     * 待办列表查询项目信息
     * selectType  1 监护大纲类 2 征询类  3 许可类  4 专项保护方案类
     *
     * @param
     * @return()
     */
    @RequestMapping(value = "/report/selectIssueProjectList")
    public MessageBean selectIssueProjectList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
            String userNumber = JwtTokenUtils.getUserNumber(tokenHeader.substring(JwtTokenUtils.TOKEN_PREFIX.length()));

            Integer pageNum = (Integer) map.get("page");
            Integer pageSize = (Integer) map.get("limit");
            String selectType = (String) map.get("selectType");
            String agenda = (String) map.get("agenda");
            //编号
            String noSelect = null;
            if (!HandlerNullUtils.objectIsNull(map.get("no"))) {
                noSelect = (String) map.get("no");
            }
            //项目名称
            String projectNameSelect = null;
            if (!HandlerNullUtils.objectIsNull(map.get("projectName"))) {
                projectNameSelect = (String) map.get("projectName");
            }
            //已办|待办（状态）
            String reviewStatus = null;
            if (!HandlerNullUtils.objectIsNull(map.get("reviewStatus"))) {
                reviewStatus = (String) map.get("reviewStatus");
            }
            //流程流转状态
            String status=null;
            if(!HandlerNullUtils.objectIsNull(map.get("status"))){
                status = (String) map.get("status");
            }
            pageNum = pageNum == null ? 1 : pageNum;
            pageSize = pageSize == null ? 10 : pageSize;
            int pageNumInt = pageNum;
            int pageSizeInt = pageSize;
            PageHelper.startPage(pageNumInt, pageSizeInt);
            List<Project>  projectList = reportProjectService.selectIssueProject(BusinessConstant.VERSION_TYPE_NEW, selectType, userNumber, noSelect, projectNameSelect, reviewStatus,agenda,status);

            PageInfo<Project> page = new PageInfo<>(projectList);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("projectList", page);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("列表查询项目信息成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("列表查询项目信息失败");
        }
        return messageBean;
    }


    /**
     * 通过UUId获取项目的详情信息
     *
     * @return
     */
    @RequestMapping(value = "/report/getProgramInfoByUuid")
    public MessageBean getProgramInfoByUuid(@RequestBody Map<String, Object> map) {
        MessageBean messageBean = new MessageBean();
        String uuid;
        String selectType;
        try {
            if (!HandlerNullUtils.objectIsNull(map.get("uuid")) && !HandlerNullUtils.objectIsNull(map.get("selectType"))) {
                uuid = (String) map.get("uuid");
                selectType = (String) map.get("selectType");
            } else {
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("获取项目的详情信息失败 请输入有效项目UUID");
                return messageBean;
            }
            Map<String, Object> dataMap = new HashMap<String, Object>();
            Project project = reportProjectService.getProgramInfoByUuid(uuid, selectType);
            //全部的文件  保含工程信息概况
            List<File> fileLists = reportProjectService.getFileInfoByProjectUuid(uuid);
            // 获取项目附件上传接口
            List<TechnicalAccessory> technicalAccessoryList = technicalAdviceService.getTechnicalAccessoryListByProjectUuid(uuid);

            List<Map<String, Object>> maps = reportProjectService.engineeringInformationSummary(map);

            project.setFiles(fileLists);
            dataMap.put("project", project);
            dataMap.put("technicalAccessoryList", technicalAccessoryList);
            dataMap.put("summary", maps);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("获取项目的详情信息成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("获取项目的详情信息失败");
        }
        return messageBean;
    }

    /**
     * 通过NO获取历史项目信息列表
     *
     * @return
     */
    @RequestMapping(value = "/report/getProgramInfoListByNo")
    public MessageBean getProgramHisInfoListByNo(@RequestBody Map<String, Object> map) {

        MessageBean messageBean = new MessageBean();
        String no = null;
        try {
            if (!HandlerNullUtils.objectIsNull(map.get("no"))) {
                no = (String) map.get("no");
            } else {
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("获取历史项目信息列表失败 请输入有效项目no");
                return messageBean;
            }
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<Project> projectList = reportProjectService.getProgramHisInfoListByNo(no);
            //List<File> fileLists = reportProjectService.getProgramInfoListByNo(no);
            //project.setFiles(fileLists);
            dataMap.put("projectList", projectList);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("获取历史项目信息列表成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("获取历史项目信息列表失败");
        }
        return messageBean;
    }


    /**
     * 获取代办状态列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/report/getTodoStatusList")
    public MessageBean getTodoStatusList(@RequestBody Map<String, Object> map) {

        MessageBean messageBean = new MessageBean();
        try {
            Map<String, String> todomap = new HashMap<String, String>();
            todomap = BusinessConstant.reviewStatusMap;

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("todomap", todomap);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("获取代办状态列表列表成功");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("获取代办状态列表列表失败");
        }
        return messageBean;
    }

    /**
     * 通过项目附件ID下载附件
     *
     * @return
     */
    @GetMapping(value = "/report/downLoadProjectotherattachFileByAessName")
    public void downLoadProjectotherattachFileByAessName(HttpServletResponse response, @RequestParam Map<String, Object> map) {

        try {
            //附件名字
            String aessName = (String) map.get("aessName");
            ObjectStat objectStat = minIoUtil.getObjectStat(projectotherattach, aessName);
            response.setContentType(objectStat.contentType());
            response.setCharacterEncoding("UTF-8");
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(aessName, "UTF-8"));
            //文件流
            InputStream object = minIoUtil.getObject(projectotherattach, aessName);
            IOUtils.copy(object, response.getOutputStream());

            object.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过uuid删除项目附件
     *
     * @return
     */
    @RequestMapping(value = "/report/deleteProjectotherattachFileByUuid")
    public MessageBean deleteProjectotherattachFileByUuid(@RequestBody Map<String, Object> map) {

        MessageBean messageBean = new MessageBean();
        try {
            String aessId = (String) map.get("aessId");

            Map<String, Object> dataMap = new HashMap<String, Object>();

            reportProjectService.deleteProjectotherattachFileByUuid(aessId);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("通过uuid删除项目附件成功");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("通过uuid删除项目附件失败");
        }
        return messageBean;
    }

    /**
     * 退回替换技审文件
     */
    @RequestMapping(value = "/report/replaceFile")
    public MessageBean replaceFile(@RequestBody Project project) {
        MessageBean messageBean = new MessageBean();
        try {
            List<File> files = project.getFiles();
            String no = project.getNo();
            String version_type = "1";
            String type = project.getType();
            Map<String, String> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("no", no);
            objectObjectHashMap.put("versionType", version_type);
            objectObjectHashMap.put("type", type);
            List<Project> projects = reportProjectService.projectSelect(objectObjectHashMap);
            // 返回工程信息的UUID
            if (projects.size() == 0) {
                messageBean.setType(MessageConstant.FAIL_TYPE);
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("项目在技审不存在");
                return messageBean;
            }
            String uuid = projects.get(0).getUuid();
            // 根据UUID查询当前下发次数
            Map<String, Object> stringIntegerMap = reportProjectService.saverFileNumber(uuid);
            // 监护大纲下次次数
            Integer outlineNumber = Integer.valueOf(stringIntegerMap.get("outline_number").toString());
            // 技审意见下发次数
            Integer flowNumber = Integer.valueOf(stringIntegerMap.get("flow_number").toString());
            // 监护大纲
            Integer outlineStatus = Integer.valueOf(projects.get(0).getOutlineStatus());
            // 技审意见
            Integer flow_status = Integer.valueOf(projects.get(0).getFlowStatus());
            // 更改监护档案状态
            if (outlineStatus < 4) {
                objectObjectHashMap.put("outlineStatus", "1");
                reportProjectService.updateProjectVersionStatus(objectObjectHashMap);
                outlineNumber = outlineNumber + 1;

            }
            // 更改技审意见状态
            if (flow_status < 4) {
                objectObjectHashMap.put("flowStatus", "1");
                reportProjectService.updateProjectVersionStatus(objectObjectHashMap);
                flowNumber = flowNumber + 1;
            }

            project.setUuid(uuid);
            for (File file : files) {
                String fileI = UUIDUtils.getUUID();
                file.setId(fileI);//技审文件ID
                file.setProjectUuid(uuid); //技审项目编号
                file.setNo(project.getNo()); //项目编号
                file.setOutlineNumber(outlineNumber);
                file.setFlowNumber(flowNumber);
            }
            //判断报审过来的文件是否为空
            if (!HandlerNullUtils.objectIsNull(files)) {
                reportProjectService.addFileInfo(files, project.getManagerNumber());
            }

            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("更新项目信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("更新项目信息失败");
        }
        return messageBean;
    }


    /**
     * 完结项目文档查询
     */
    @RequestMapping(value = "/report/replacepdf")
    public MessageBean replacepdf(@RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token,@RequestBody Map<String, String> map) {
        MessageBean messageBean = new MessageBean();
        try {
            map.put("token", token);
            String replacepdf = reportProjectService.replacepdf(map);
            Map<String, String> map1=new HashMap<>();
            map1.put("url",replacepdf);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("项目信息查询成功");
            messageBean.setData(map1);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("项目信息查询失败");
        }
        return messageBean;
    }

    /**
     * 根据类型得到相应的下拉内容
     */
    @RequestMapping(value = "/report/pullDownServer")
    public MessageBean pullDown(@RequestBody Map<String, String> map) {
        MessageBean messageBean = new MessageBean();
        try {
            List<Map<String, Object>> map2 = reportProjectService.pullDownServer(map);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("信息查询成功");
            messageBean.setData(map2);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("信息查询失败");
        }
        return messageBean;
    }









}
